package com.zz.service;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zz.repository.Userrole.Userrole;
import com.zz.repository.Userrole.UserroleRepository;
import com.zz.repository.user.User;
import com.zz.repository.user.UserRepository;
import com.zz.utils.Encrypt;


@Service
public class UserService {
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private UserroleRepository userroleRepository;
	
	public String addUser(User userinfo){
		if(userinfo.getWeixinid() == null || "".equals(userinfo.getWeixinid())) return "微信公众号不能为空！";
		if(userinfo.getUsername() == null || "".equals(userinfo.getUsername())) return "用户名不能为空！";
		if(userinfo.getPassword() == null || "".equals(userinfo.getPassword())) return "密码不能为空！";
		User users = userRepository.findOneByUsername(userinfo.getUsername());
		if(users != null) {
			users = null;
			return "用户名已经存在！";
		}
		users = userRepository.findOneByWeixinid(userinfo.getWeixinid());
		if(users != null) {
			users = null;
			return "微信公众号已经存在！";
		}
		Userrole role = userroleRepository.findOne((long) 1);
		String shaPass = Encrypt.SHA512(userinfo.getPassword());
		try {
			userinfo.setPassword(shaPass);
			userinfo.setRole(role);
			userRepository.save(userinfo);
			return "添加成功！";
		} catch (Exception e) {
			return "添加会员失败！";
		}
	}
	public User login(User userinfo) {
		return userRepository.findOneByUsername(userinfo.getUsername());
	}
	public Object validate(User userinfo, Integer flg) {
		Map<Object, Object> json = new HashMap<Object, Object>();
		User users = userRepository.findOneByUsername(userinfo.getUsername());
		if(flg == 1){
			if(users == null) {
				json.put("info", "用户名不存在");
				json.put("dlu", false);
			}
		}
		return json;
	}
}
